package com.demo.zhihu.service;

import javax.inject.Singleton;

import com.demo.zhihu.data.QuestionDao;
import com.demo.zhihu.data.UserDao;
import com.demo.zhihu.model.Answer;
import com.demo.zhihu.model.Comment;
import com.demo.zhihu.model.Like;
import com.demo.zhihu.model.Question;
import com.demo.zhihu.model.User;

import cn.techarts.dragonfly.app.AbstractService;
import cn.techarts.dragonfly.data.trans.Transactional;

@Singleton
public class QuestionServiceImpl extends AbstractService implements QuestionService {
	
	@Override
	@Transactional
	public Question ask(int asker, String title, String summary) {
		var param = new Question(asker,title,summary);
		var dao = this.getMapper(QuestionDao.class);
		dao.askQuestion(param);
		var userDao = this.getMapper(UserDao.class);
		userDao.setUserQuestions(new User(asker, 1, 0));
		return param;
	}
	
	@Override
	@Transactional
	public Answer answer(int question, int user, String content) {
		var param = new Answer(question, user, content);
		var dao = this.getMapper(QuestionDao.class);
		var asker = dao.getQuestionAsker(question);
		if(asker != null && asker == user) return null;
		if(dao.doesUserAnswered(param) != 0) return null;
		dao.answerQuestion(param);
		dao.setQuestionAnswers(new Question(question, 1));
		var userDao = this.getMapper(UserDao.class);
		userDao.setUserAnswers(new User(user, 0, 1));
		return param;
	}
	
	
	
	@Transactional
	public Comment reply(int comment, int commenter, String content) {
		var param = new Comment(Comment.ME, comment, commenter, content);
		var dao = getMapper(QuestionDao.class);    
		dao.postComment(param);
		return param;		
	}
	
	@Transactional
	public Comment comment(int answer, int commenter, String content) {
		var param = new Comment(Answer.ME, answer, commenter, content);
		var dao = getMapper(QuestionDao.class);
		dao.postComment(param);
		dao.setAnswerComments(new Answer(answer, 1));
		return param;
	}
	
	@Override
	@Transactional
	public boolean likeSomeone(int type, int id, int user) {
		var param = new Like(user, type, id);
		var dao = getMapper(QuestionDao.class);
		if(dao.didUserLikeSomeone(param) == 0) {
			param.setCanceled(false);
			dao.likeSomeone(param);
		}else {
			param.setCanceled(true);
			dao.dislikeSomeone(param);
		}
		
		if(type == Answer.ME) {
			dao.setAnswerLikes(param);
			var tmp = dao.getAnswerer(id);
			if(tmp == null) return false;
			param.setUser(tmp);
			dao.setUserLikes(param);
		}else {
			dao.setCommentLikes(param);
		}
		return true;		
	}
}
